<?php
namespace Com\Pay;

//畅捷支支付

class ChangJiePay{

    private $config = array();

    public function __construct($mchConfig,$config = null){
        $this->config = $mchConfig;
    }


    /*生成支付连接*/
    public function getUrl($order_info){
        $merchantCode = $this->config['mch_id'];
        $price = $order_info['paymoney'];
        $notifyUrl = 'http://' . $_SERVER['HTTP_HOST'].'/Api/NotifyCallback/ChangjieNotify';
        $order_sn = $order_info['ordernumber'];
        // 基础参数
        $base_data = array(
            'Service' =>   'mag_pub_sinm_pay',
            'Version'    =>     '1.0',
            'PartnerId'     =>  $merchantCode,
            "InputCharset"        =>  'utf-8',
            "TradeDate"  =>  date("Ymd"),
            "TradeTime"  =>  date("His"),
            "SignType"  =>  'RSA',
            "ReturnUrl"  =>  $order_info['return_url'],
        );

        // 微信一户一码参数
        $pxoData = array(
            'OutTradeNo' => $order_sn,
            'MchId' => $merchantCode,
            'TradeType' => 11,
            'AppId'  => $this->config['appid'],
            'BuyerPayCode' => $order_info['openid'],
            'Currency'  => 'CNY',
            'TradeAmount' => $price,
            'GoodsName' => 'ChangbaoGzh',
            'Subject'  => 'ChangbaoGzh',
            'OrderStartTime' => date('YmdHis'),
            'NotifyUrl' => $notifyUrl,
            'SpbillCreateIp' => get_client_ip(),
        );
        $post = array_merge($base_data,$pxoData);
        $Sign = $this->rsaSign($post);
        $post['Sign'] = $Sign;
        $send_url = 'https://pay.chanpay.com/mag-unify/gateway/receiveOrder.do';
//        dump($post);die;
        $result = $this->curl_post($send_url,$post);
        $result = json_decode($result , true);
        if($result['RetCode'] == 'SYSTEM_SUCCESS'){
            $jsparams = array(
                'appId' => $result['JsapiAppId'],
                'timeStamp' => $result['JsapiTimeStamp'],
                'nonceStr' => $result['JsapiNonceStr'],
                'package' => $result['JsapiPackage'],
                'signType' => $result['JsapiSignType'],
                'paySign' => $result['JsapiPaySign'],
            );
            return $jsparams;
        }
        return false;
    }

    //回调方法，把返回数据处理成统一规定返回
    public function response(){
        $data = parseData();
        $temp='';
        ksort($data);//对数组进行排序
        //遍历数组进行字符串的拼接
        $data['extension'] = json_encode(json_decode($data['extension'] , true) , JSON_UNESCAPED_UNICODE);
        foreach ($data as $x=>$x_value){
            if ($x != 'sign' && $x != 'sign_type' && $x != 'PHPSESSID' && $x_value != ''){
                $temp = $temp.$x."=".$x_value."&";
            }
        }
        $temp = rtrim($temp,'&');
        if($this->rsaVerify($temp , $data['sign'])){
            // 支付成功，签名验证成功
                return true;
        }else{
            // 失败
            return false;
        }
    }

    public function curl_post($url, $data)
    {
        $data = http_build_query($data);
        // file_put_contents('./tmp.txt',$data);
        //echo '<br>'.$data.'<br>';
        // mb_strlen($str,'utf-8');
        // var_dump((mb_strlen($data,'utf-8') == strlen($data)));
        $opts = array(
            'http'=>array(
                'method'=>"POST",
                'timeout'=>60,
                'header'=>"Content-type: application/x-www-form-urlencoded\r\n".
                    "Content-length:".mb_strlen($data,'utf-8')."\r\n" .
                    "Cookie: foo=bar\r\n" .
                    "\r\n",
                'content' => $data,
            )
        );
        $cxContext = stream_context_create($opts);
        $result = file_get_contents($url, false, $cxContext);
        return $result;
    }

    private function gbkToUtf8($arr){
        if(is_array($arr)){
            $res = array();
            foreach($arr as $k => $v){
                $res[$k] = $this->gbkToUtf8($v);
            }
            return $res;
        }else{
            return mb_convert_encoding ( $arr, "UTF-8", "GBK" );
        }
    }


   private function rsaSign($args) {
//        $args=array_filter($args);//过滤掉空值
        ksort($args);
        $query  =   '';
        foreach($args as $k => $v){
            if($k == 'SignType') continue;
            $query = $query . $k .'=' . $v . '&';
        }
        $query = rtrim($query , '&');
        $private_key = openssl_get_privatekey(file_get_contents(getcwd().'/ThinkPHP/Library/Vendor/Changjiepay/cert/Cb_private_key.pem'));
        $pkeyid = openssl_get_privatekey($private_key);
        openssl_sign($query, $sign, $pkeyid);
        openssl_free_key($pkeyid);
        $sign = base64_encode($sign);
        return $sign;
    }

    /*
    * 验证签名
    * @param $prestr 需要签名的字符串
    * @param $sign 签名结果
    * return 签名结果
    */
   private function rsaVerify($prestr, $sign) {
        $sign = base64_decode($sign);
        $pkeyid = openssl_get_publickey(file_get_contents(getcwd().'/ThinkPHP/Library/Vendor/Changjiepay/cert/Cb_public_key.pem'));
        if ($pkeyid) {
            $verify = openssl_verify($prestr, $sign, $pkeyid);
            openssl_free_key($pkeyid);
        }
        if($verify == 1){
            return true;
        }else{
            return false;
        }
    }


}
